import { Component, EventEmitter, Input, Output } from '@angular/core';
import { Router } from '@angular/router';
import { HttpService } from '../../../service/http.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { AngularEditorConfig } from '@kolkov/angular-editor';
import { SharedData } from './sharedData';
import { NzModalService } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-addlog',
  templateUrl: './addlog.component.html',
  styleUrls: ['./addlog.component.css'],
})
export class AddlogComponent {
  public studyInfo = {
    id: 0,
    name: '',
    logDate: new Date(),
    comment: '',
    categoryName: '', // 分类字段
    content: '', // 内容字段
    userId: 0,
    tagName: [] as string[], // 标签字段
    statusName: '',
  };

  public isTagManagerVisible: boolean = false;

  constructor(
    private router: Router,
    private httpService: HttpService,
    private modalService: NzMessageService,
    private sharedData: SharedData,
    private modal: NzModalService
  ) {}

  trackOption = (index: number, item: string) => item;

  public categories: any[] = [];
  private memoryCategories: any[] = [];
  private defaultCategory: string = '';
  private customCategory: string = '';
  private defaultCategories: string[] = [];
  public categoryExists = false;

  private categoryIdCounter = 1000; // 新增分类临时 ID 起始
  public isSubmitting: boolean = false; // 防止重复提交

  public tags: any[] = [];
  private defaultTag: string = '';
  private customTag: string = '';
  private memoryTages:any[] = [];
  public newTagName: string = ''; // 存储用户输入的标签名称
  public customTags: any[] = []; // 自定义标签列表

  status: any[] = [];  // 用于存储获取到的状态列表
  selectedStatusId: number | null = null;  // 用于绑定选中的状态ID

  @Output() categoryNameChange = new EventEmitter();

  public userDetails: any = {};
  public sendButton = false;

  editorConfig: AngularEditorConfig = {
    editable: true,
    spellcheck: true,
    height: '300px',
    minHeight: '200px',
    maxHeight: '600px',
    width: 'auto',
    minWidth: '0',
    translate: 'yes',
    enableToolbar: true,
    showToolbar: true,
    placeholder: 'Enter text here...',
    defaultParagraphSeparator: '',
    defaultFontName: '',
    defaultFontSize: '',
    fonts: [
      { class: 'arial', name: 'Arial' },
      { class: 'times-new-roman', name: 'Times New Roman' },
      { class: 'calibri', name: 'Calibri' },
      { class: 'comic-sans-ms', name: 'Comic Sans MS' },
    ],
    customClasses: [
      {
        name: 'quote',
        class: 'quote',
      },
      {
        name: 'redText',
        class: 'redText',
      },
      {
        name: 'titleText',
        class: 'titleText',
        tag: 'h1',
      },
    ],
    uploadUrl: 'v1/image',
    sanitize: true,
    toolbarPosition: 'top',
    toolbarHiddenButtons: [['bold', 'italic'], ['fontSize']],
  };


  ngOnInit(): void {
    const user = localStorage.getItem('user');
    if (user != null) {
      this.userDetails = JSON.parse(user);
      this.studyInfo.userId = Number(this.userDetails.id);
    } else {
      this.router.navigate(['/login']);
    }

    this.loadCategories();
    this.loadTags();
    this.loadStatus();
  }

  loadCategories(): void {
    this.httpService.get('/rest/categories').subscribe(
      (res: any) => {
        if (res.data && res.data.length > 0) {
          this.categories = res.data;
          this.defaultCategories = [...this.categories];
          console.log('加载的分类:', this.categories);
        } else {
          this.modalService.error('获取分类数据失败！');
        }
      },
      (error) => {
        this.modalService.error('请求分类数据出错！');
      },
    );
  }

  searchText = '';

  onSearchInput(value: string) {
    console.log(value);
    this.searchText = value.trim();
    console.log(this.searchText);
    this.sharedData.updateData(value.trim());
  }

  handleCategoryInput(): void {
    this.defaultCategory = '';
    this.customCategory = '';
    const input = this.searchText?.trim();
    if (this.categories.includes(input)) {
      this.defaultCategory = input;
    } else {
      this.customCategory = input;
      this.memoryCategories.push(input);
    }
  }

  addItem(input: HTMLInputElement): void {
    const value: string = input.value.trim();
    if (!value) return;

    // 如果分类不存在，才添加
    if (this.categories.findIndex((c) => c.categoryName === value) === -1) {
      const payload = { categoryName: value, isCustom: 1 };

      this.httpService.post('/rest/category', payload).subscribe(
        (res: any) => {
          console.log('添加返回：', res);
          if (res.code === '0000') {
            // 使用后端返回的新分类对象
            const newCategory = res.data;
            this.categories = [...this.categories, newCategory];
            this.memoryCategories.push(newCategory.categoryName);
            this.modalService.success('自定义分类添加成功');
            input.value = ''; // 清空输入框
          } else {
            this.modalService.error(
              '添加分类失败：' + (res.message || '未知错误'),
            );
          }
        },
        (error) => {
          this.modalService.error('请求失败，无法添加分类');
        },
      );
    } else {
      this.modalService.info('该分类已存在');
    }
  }

  addCustomCategory() {
    const length: number = this.categories.length;
    const newCategory = {
      id: length + 100,
      categoryName: this.searchText,
      isCustom: 1,
    };

    this.categories.push(newCategory);
    this.memoryCategories.push(this.searchText);

    // 打印所有分类，确认 isCustom 是否添加成功
    console.log(this.categories);
  }

  deleteCategory(category: any): void {
    // 删除自定义分类
    if (category.isCustom === 0) {
      this.modalService.warning('默认分类无法删除');
      return;
    }

    // 调用后端接口删除
    this.httpService
      .delete(`/rest/category/${category.categoryName}`)
      .subscribe(
        (res: any) => {
          console.log(res);
          if (res.code === '0000') {
            this.categories = this.categories.filter(
              (c: any) => c.id !== category.id,
            );
            this.modalService.success('分类已删除');
          } else {
            this.modalService.error('分类删除失败');
          }
        },
        (error: any) => {
          this.modalService.error('删除分类时出错');
        },
      );
  }

  loadTags(): void {
    this.httpService.get('/rest/tags').subscribe(
      (res: any) => {
        if (res.data && res.data.length > 0) {
          this.tags = res.data;
          this.tags = [...this.tags];
          console.log('加载的标签:', this.tags);
        } else {
          this.modalService.error('获取标签数据失败！');
        }
      },
      (error) => {
        this.modalService.error('请求标签数据出错！');
      },
    );
  }

  handleTagInput(): void {
    this.defaultTag = '';
    this.customTag = '';
    const input = this.searchText?.trim();
    if(this.tags.includes(input)) {
      this.defaultTag = input;
    } else {
      this.customTag = input;
      this.memoryTages.push(input);
    }
  }

  addCustomTag() {
    const length: number = this.tags.length;
    const newTag = {
      id: length + 100,
      tagName: this.searchText,
      isCustom: 1,
    };

    this.tags.push(newTag);
    this.memoryTages.push(this.searchText);

    // 打印所有分类，确认 isCustom 是否添加成功
    console.log(this.tags);
  }

  handleTagModelChange(newValues: string[]) {
    const newTags = newValues.filter(tagName => !this.tags.some(t => t.tagName === tagName));

    for (const tagName of newTags) {
      const isCustomTag = this.isCustomTag(tagName);
      const payload = { tagName, isCustom: 1 };

      if (!isCustomTag) {
        payload.isCustom = 0;
      }

      this.httpService.post('/rest/tag/add', payload).subscribe(
        (res: any) => {
          if (res.code === '0000') {
            const newTag = res.data && res.data.tagName ? res.data : { tagName };
            this.tags = [...this.tags, newTag];
            this.modalService.success(isCustomTag ? '自定义标签添加成功' : '默认标签添加成功');
          } else {
            this.modalService.error('添加标签失败：' + (res.message || '未知错误'));
          }
        },
        () => {
          this.modalService.error('请求失败，无法添加标签');
        }
      );
    }
  }

  isCustomTag(tagName: string): boolean {
    // 判断标签是否在已有标签列表中，若不在则为自定义标签
    return !this.tags.some(t => t.tagName === tagName);
  }

  isVisible = false;
  isConfirmLoading = false;

  showModal1(): void {
    this.isVisible = true;
  }

  handleOk(): void {
    this.isConfirmLoading = true;
    setTimeout(() => {
      this.isVisible = false;
      this.isConfirmLoading = false;
    }, 2000);
  }

  handleCancel(): void {
    this.isVisible = false;
  }

  deleteTag(tag: any): void {
    if (tag.isCustom === 0) {
      this.modalService.warning("默认标签无法删除");
      return;
    }

    this.httpService
      .delete(`/rest/tag/${tag.tagName}`)
      .subscribe(
        (res:any)=> {
          console.log(res);
          if(res.code === '0000') {
            this.tags = this.tags.filter(
              (c: any)=> c.id !== tag.id,
            );
            this.modalService.success("标签已删除");
          } else {
            this.modalService.error("标签删除失败");
          }
        },
        (error:any) => {
          this.modalService.error("删除标签时出错");
        },
      );
  }

  loadStatus(): void {
    this.httpService.get(`/rest/status`).subscribe(
      (res: any) => {
        if (res.data && res.data.length > 0) {
          this.status = res.data;
          this.status = [...this.status];
          console.log('加载的状态:', this.status);
        } else {
          this.modalService.error('获取状态数据失败!');
        }
      },
      (error) => {
        console.log('请求失败:', error);
        this.modalService.error('请求状态数据失败!');
      }
    );
  }

  backToList() {
    this.router.navigate(['/loglist']);
  }

  add() {
    const url = '/rest/study';

    if (!this.studyInfo.name?.trim()) {
      this.modalService.error('标题不能为空！');
      return;
    }
    if (!this.studyInfo.logDate) {
      this.modalService.error('日期不能为空！');
      return;
    }
    if (!this.studyInfo.content?.trim()) {
      this.modalService.error('内容不能为空！');
      return;
    }
    if (!this.studyInfo.categoryName?.trim()) {
      this.modalService.error('分类不能为空！');
      return;
    }
    if (!this.studyInfo.tagName || this.studyInfo.tagName.length === 0) {
      this.modalService.error('标签不能为空！');
      return;
    }

    this.sendButton = true;
    const data = {
      content: this.studyInfo.content,
      logDate: this.studyInfo.logDate,
      name: this.studyInfo.name,
      userId: this.studyInfo.userId,
      categoryName: this.studyInfo.categoryName,
      tagName:this.studyInfo.tagName,
      statusName:this.studyInfo.statusName,
    };

    this.httpService.post(url, data).subscribe((res: any) => {
      this.router.navigate(['/loglist']);
    });
  }
}
